import {defineStore} from "pinia";

const color2rgb = (color: string) => {
    return color.startsWith('#') ? hex2rgb(color) : rgb2rgb(color)
}

// rgb(255, 0, 0) | rgba(255, 0, 0) => [255, 0, 0]
const rgb2rgb = (color: string) => {
    const colors = color.split('(')[1].split(')')[0].split(',')
    return colors.slice(0, 3).map(item => parseInt(item.trim()))
}

// #FF0000 => [255, 0, 0]
const hex2rgb = (color: string) => {
    color = color.replace('#', '')
    const matchs = color.match(/../g)

    const rgbs: number[] = []
    for (let i = 0; i < matchs!.length; i++) {
        rgbs[i] = parseInt(matchs![i], 16)
    }

    return rgbs
}

const rgb2hex = (r: number, g: number, b: number) => {
    const hexs = [r.toString(16), g.toString(16), b.toString(16)]

    for (let i = 0; i < hexs.length; i++) {
        if (hexs[i].length === 1) {
            hexs[i] = '0' + hexs[i]
        }
    }

    return '#' + hexs.join('')
}

// 颜色变亮
const lighten = (color: string, level: number) => {
    const rgbs = color2rgb(color)

    for (let i = 0; i < rgbs.length; i++) {
        rgbs[i] = Math.floor((255 - rgbs[i]) * level + rgbs[i])
    }

    return rgb2hex(rgbs[0], rgbs[1], rgbs[2])
}

// 颜色变暗
const darken = (color: string, level: number) => {
    const rgbs = color2rgb(color)

    for (let i = 0; i < rgbs.length; i++) {
        rgbs[i] = Math.floor(rgbs[i] * (1 - level))
    }

    return rgb2hex(rgbs[0], rgbs[1], rgbs[2])
}

const useColorStore = defineStore('appcolor', {
    state: () => {
        const primary = '#409eff'

        return {
            primary,
        }
    },

    persist: true,

    getters: {
        primaryPredefines(): string[] {
            return ['#FF0000 ', '#FF7F00', '#FFFF00 ', '#00FF00 ', '#00FFFF ', '#0000FF', '#8B00FF']
        }
    },

    actions: {
        primaryChange(val: string | null) {
            if (!val) return

            const el = document.documentElement
            // el.style.setProperty('--el-color-primary', val)

            el.style.setProperty('--el-color-primary', val)

            const lights = [3, 5, 7, 8, 9]
            for (const light of lights) {
                el.style.setProperty(`--el-color-primary-light-${light}`, lighten(val, light / 10))
            }

            el.style.setProperty('--el-color-primary-dark-2', darken(val, 0.2))

            const rgbs = color2rgb(val)
            el.style.setProperty('--el-color-primary-rgb', `${rgbs[0]},${rgbs[1]},${rgbs[2]}`)
        },

        primarySave(val: string | null) {
            if (!val) return

            this.primary = val
        }
    }
})
export default useColorStore
